package com.cindata

import groovy.transform.EqualsAndHashCode
import groovy.transform.ToString

@EqualsAndHashCode(includes = 'username')
@ToString(includes = 'username', includeNames = true, includePackage = false)
class User implements Serializable
{
    private static final long serialVersionUID = 1

    transient springSecurityService

    String username
    String password

    String fullName

    boolean enabled = true
    boolean accountExpired = false
    boolean accountLocked = false
    boolean passwordExpired = false

    String cellphone
    String email
    String externalId

    String appSessionId

    String avatarUrl
    Integer skin = 0

    //    User reportTo

    String verificationCode

    Date lastPasswordModifiedDate

    Boolean loginBySms = false

    Boolean fixedIp = false

    String ip

    Boolean dynamicMenu = false

    User reportTo
    Account account
    // 用户所属机构

    Department department

    Date createdDate = new Date()
    Date modifiedDate = new Date()

    Date expiredDate

    User(String username, String password)
    {
        this()
        this.username = username
        this.password = password
    }

    Set<Role> getAuthorities()
    {
        UserRole.findAllByUser(this)*.role
    }

    def isGD()
    {
        def r = Role.findByAuthority('ROLE_GD_LOGO')
        def query = UserRole.where {
            user == this
            role == r
        }
        def ur = query.find()
        if (ur)
        {
            return true
        }
        else
        {
            return false
        }
    }

    def isYC()
    {
        def r = Role.findByAuthority('ROLE_YCLOAN')
        def query = UserRole.where {
            user == this
            role == r
        }
        def ur = query.find()
        if (ur)
        {
            return true
        }
        else
        {
            return false
        }
    }

    // 获得菜单数组
    def getMenuArr()
    {
        def menuArr
        def adminRole = Role.findByAuthority("ROLE_ADMINISTRATOR")
        def userRoleArr = UserRole.where {
            user == this
        }.role.list()
        def adminUserRole = UserRole.where {
            user == this
            role == adminRole
        }.find()
        if (userRoleArr && userRoleArr.size() > 0)
        {
            // 有角色信息
            if (adminUserRole)
            {
                // 超管
                menuArr = Menu.where {
                    status == 1
                    url != '/main/index1'
                }.list(sort: "orderNum")
            }
            else
            {
                menuArr = RoleMenu.where {
                    role in userRoleArr
                    menu.status == 1
                }.menu.list().sort { a, b -> a.orderNum < b.orderNum ? -1 : 1 }
            }
        }
        else
        {
            // 无角色信息
            def firstPage = Menu.findByTitle('首页')
            menuArr = [firstPage]
        }
        return menuArr
    }

    def beforeInsert()
    {
        encodePassword()
    }

    def beforeUpdate()
    {
        if (isDirty('password'))
        {
            encodePassword()
        }
    }

    protected void encodePassword()
    {
        password = springSecurityService?.passwordEncoder ? springSecurityService.encodePassword(password) : password
    }

    static transients = ['springSecurityService']

    static constraints = {

        skin nullable: true, blank: true

        createdDate nullable: true, blank: true
        modifiedDate nullable: true, blank: true
        password blank: false, password: true, minSize: 6, maxSize: 256
        //        , matches: "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=\\S+\$).{8,}\$"
        username blank: false, unique: true
        fullName blank: true, nullable: true

        cellphone size: 11..11, blank: true, nullable: true //, unique: true
        email blank: true, nullable: true //, unique: true
        externalId blank: true, nullable: true //, unique: true

        appSessionId blank: true, nullable: true //, unique: true

        avatarUrl nullable: true, blank: true, maxSize: 256

        //        securityProfile blank: true, nullable: true

        verificationCode blank: true, nullable: true, maxSize: 16

        ip blank: true, nullable: true, maxSize: 64

        lastPasswordModifiedDate blank: true, nullable: true

        dynamicMenu blank: true, nullable: true

        reportTo blank: true, nullable: true

        account blank: true, nullable: true, comment: '所属机构'
        expiredDate blank: true, nullable: true

        department blank: true, nullable: true
    }

    static mapping = {
        table 'login_user'
        password column: '`password`'
    }

    // 获得当前用户所管理的机构
    def getCurUserManageAccount()
    {
        //登录用户
        def userAccount = this.account
        if (!userAccount)
        {
            return []
        }
        def accountList = Account.where {
            id in AccountManageAccount.where {
                account.id == userAccount.id
            }.manageAccount
        }.list()
        return accountList
    }
}